﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hinacom.Scheduler.Manager.Utilities
{
    public class RepeatInterval
    {
        private RepeatIntervalUnit unit = RepeatIntervalUnit.Hours;

        public int IntervalValue { get; set; }
        public RepeatIntervalUnit IntervalUnit
        {
            get { return this.unit; }
            set { this.unit = value; }
        }
        public TimeSpan ToTimeSpan()
        {
            long ticks = Convert.ToInt64(this.IntervalValue) * this.IntervalUnit.Weight;
            return new TimeSpan(ticks);
        }
        public static RepeatInterval FromTimeSpan(TimeSpan timespan)
        {
            int val = 0;
            RepeatIntervalUnit unit = RepeatIntervalUnit.Hours;
            if (timespan.Ticks > 0)
            {
                foreach (RepeatIntervalUnit u in RepeatIntervalUnit.Units)
                {
                    double v = Convert.ToDouble(timespan.Ticks) / u.Weight;

                    val = Convert.ToInt32(v);
                    unit = u;

                    if (v >= 1 && (v % 1) == 0)
                        break;
                }
            }
            return new RepeatInterval() { IntervalValue = val, IntervalUnit = unit };
        }
        public override string ToString()
        {
            return this.IntervalValue.ToString() + " " + this.IntervalUnit.ToString().ToLower();
        }
    }

    public struct RepeatIntervalUnit
    {
        private RepeatIntervalUnit(string display, long weight)
        {
            this._display = display;
            this._weight = weight;
        }
        
        private string _display;
        private long _weight;

        public string Display
        {
            get { return this._display; }
        }
        public long Weight
        {
            get { return this._weight; }
        }

        public static RepeatIntervalUnit Hours = new RepeatIntervalUnit("Hour(s)", 10000L * 1000 * 60 * 60);
        public static RepeatIntervalUnit Minutes = new RepeatIntervalUnit("Minute(s)", 10000L * 1000 * 60);
        public static RepeatIntervalUnit Seconds = new RepeatIntervalUnit("Second(s)", 10000L * 1000);

        public static RepeatIntervalUnit[] Units
        {
            get
            {
                return new RepeatIntervalUnit[] { Hours, Minutes, Seconds };
            }
        }
        public override string ToString()
        {
            return Display;
        }
    }

}
